package DAO;

import Damain.user;
import Utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class userDaoImpl implements userDao {


    @Override
    public user login(String username, String password) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        //将user对象赋值为null
        user user = null;

        try {
            //加载驱动
            connection = JdbcUtils.getConnection();
            //查询数据库
            String sql = "SELECT * FROM t_user WHERE username = ? AND password = ?";
            //预编译sql
            statement = connection.prepareStatement(sql);
            //设置占位符的值
            statement.setString(1, username);
            statement.setString(2, password);
            //执行
            resultSet = statement.executeQuery();
            //判断resultset中是否存在数据
            if (resultSet.next()) {
                //给user对象赋值
                user = new user();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setNickname(resultSet.getString("nickname"));

            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭链接
            JdbcUtils.close(connection, statement, resultSet);
        }
        //如果没有数据返回null,有数据返回user
        return user;
    }
}
